<template>
  <div class="member-levels-container">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span>会员等级管理</span>
          <el-button type="primary" :icon="Plus" @click="handleCreate">
            新增等级
          </el-button>
        </div>
      </template>
      
      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="等级名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入等级名称"
            clearable
            style="width: 180px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">
            搜索
          </el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 等级列表表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column prop="name" label="等级名称" width="150" />
        <el-table-column prop="level" label="等级数字" width="120" sortable>
          <template #default="{ row }">
            <el-tag>{{ row.level }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column prop="updated_at" label="更新时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.updated_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              link
              type="danger"
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
    </el-card>
    
    <!-- 等级编辑对话框 -->
    <MemberLevelDialog
      v-model="dialogVisible"
      :level-id="currentLevelId"
      @success="handleDialogSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh } from '@element-plus/icons-vue'
import { getMemberLevelList, deleteMemberLevel } from '@/api/memberLevels'
import MemberLevelDialog from '@/components/MemberLevelDialog.vue'

interface MemberLevel {
  id: string
  name: string
  level: number
  description?: string
  created_at?: string
  updated_at?: string
  [key: string]: any
}

interface SearchForm {
  name: string
}

const loading = ref(false)
const tableData = ref<MemberLevel[]>([])
const dialogVisible = ref(false)
const currentLevelId = ref<string | null>(null)

const searchForm = reactive<SearchForm>({
  name: ''
})

// 非分页列表

// 格式化日期时间
const formatDate = (dateStr: string | null | undefined): string => {
  if (!dateStr) return '-'
  try {
    const date = new Date(dateStr)
    if (isNaN(date.getTime())) return '-'
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    }).replace(/\//g, '-')
  } catch (error) {
    return '-'
  }
}

// 获取等级列表
const fetchLevelList = async (): Promise<void> => {
  loading.value = true
  try {
    const params: Record<string, any> = {}
    if (searchForm.name && searchForm.name.trim()) {
      params.name = searchForm.name.trim()
    }

    const res = await getMemberLevelList(params)
    if (res.code === 200 && res.data) {
      // 新文档：data 为数组（非分页）
      tableData.value = Array.isArray(res.data) ? res.data : (res.data.list || [])
    } else {
      ElMessage.error(res.message || '获取等级列表失败')
    }
  } catch (error) {
    console.error('获取等级列表失败:', error)
    // 错误信息已在 request 拦截器中处理
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = (): void => {
  fetchLevelList()
}

// 重置搜索
const handleReset = (): void => {
  searchForm.name = ''
  fetchLevelList()
}

// 新增等级
const handleCreate = (): void => {
  currentLevelId.value = null
  dialogVisible.value = true
}

// 编辑等级
const handleEdit = (row: MemberLevel): void => {
  currentLevelId.value = row.id
  dialogVisible.value = true
}

// 删除等级
const handleDelete = async (row: MemberLevel): Promise<void> => {
  try {
    await ElMessageBox.confirm(
      `确定要删除等级 "${row.name}" 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const res = await deleteMemberLevel({ id: row.id })
    if (res.code === 200) {
      ElMessage.success('删除成功')
      fetchLevelList()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除等级失败:', error)
      // 错误信息已在 request 拦截器中处理
    }
  }
}

// 对话框操作成功
const handleDialogSuccess = (): void => {
  fetchLevelList()
}

onMounted((): void => {
  fetchLevelList()
})
</script>

<style lang="scss" scoped>
.member-levels-container {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 600;
    font-size: 16px;
  }
  
  .search-form {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>

